#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author:Zx
@file: messages.py
@time: 2025/7/23  10:47
# @describe: 简易版-留言
"""

import os
from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify
from flask_login import login_required, current_user
from utils.data_utils import load_data, save_data
import logging
import uuid
from datetime import datetime
from werkzeug.utils import secure_filename
from config import basedir


messages_bp = Blueprint('messages', __name__)


def load_messages():
    """加载留言数据"""
    try:
        return load_data('messages.json')
    except:
        return []


def save_messages(messages):
    """保存留言数据"""
    return save_data(messages, 'messages.json')


# 在message_board路由中修改
@messages_bp.route('/message-board', methods=['GET', 'POST'])
@login_required
def message_board():
    messages = load_messages()

    # 只显示已批准的留言和回复
    filtered_messages = []
    for msg in messages:
        if msg.get('status') == 'approved' or msg['user_id'] == current_user.id:
            # 过滤回复
            approved_replies = [r for r in msg['replies'] if
                                r.get('status') == 'approved' or r['user_id'] == current_user.id]
            msg_copy = msg.copy()
            msg_copy['replies'] = approved_replies
            filtered_messages.append(msg_copy)

    if request.method == 'POST':
        content = request.form.get('content', '').strip()

        if not content:
            flash('留言内容不能为空', 'error')
        else:
            new_message = {
                'id': str(uuid.uuid4()),
                'user_id': current_user.id,
                'username': current_user.username,
                'content': content,
                'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                'status': 'approved' if current_user.role == 'admin' else 'pending',  # 管理员自动批准
                'replies': []
            }

            messages.insert(0, new_message)
            save_messages(messages)
            flash('留言已提交' + ('并发布' if current_user.role == 'admin' else '，等待审核'), 'success')
            return redirect(url_for('messages.message_board'))

    return render_template('message_board.html', active_page='messages', messages=filtered_messages)


# 新增审核路由
@messages_bp.route('/admin/messages', methods=['GET'])
@login_required
def manage_messages():
    if current_user.role != 'admin':
        flash('无权访问此页面', 'error')
        return redirect(url_for('messages.message_board'))

    messages = load_messages()
    pending_messages = []
    pending_replies = []

    # 收集待审核留言
    for msg in messages:
        if msg.get('status') == 'pending':
            pending_messages.append({
                'id': msg['id'],
                'username': msg['username'],
                'content': msg['content'],
                'created_at': msg['created_at']
            })

        # 收集待审核回复
        for reply in msg.get('replies', []):
            if reply.get('status') == 'pending':
                # 添加父留言信息
                pending_replies.append({
                    'id': reply['id'],
                    'username': reply['username'],
                    'content': reply['content'],
                    'created_at': reply['created_at'],
                    'parent_id': msg['id'],
                    'parent_username': msg['username']
                })

    return render_template('admin_messages.html',
                           messages=pending_messages,
                           replies=pending_replies)


@messages_bp.route('/admin/message/<message_id>/<action>', methods=['POST'])
@login_required
def review_message(message_id, action):
    if current_user.role != 'admin':
        return jsonify({'success': False, 'message': '无权操作'}), 403

    messages = load_messages()
    message = next((msg for msg in messages if msg['id'] == message_id), None)

    if not message:
        return jsonify({'success': False, 'message': '留言不存在'}), 404

    if action == 'approve':
        message['status'] = 'approved'
        msg = '留言已批准'
    elif action == 'reject':
        messages.remove(message)
        msg = '留言已拒绝'
    else:
        return jsonify({'success': False, 'message': '无效操作'}), 400

    save_messages(messages)
    return jsonify({'success': True, 'message': msg})


@messages_bp.route('/admin/reply/<reply_id>/<action>', methods=['POST'])
@login_required
def review_reply(reply_id, action):
    if current_user.role != 'admin':
        return jsonify({'success': False, 'message': '无权操作'}), 403

    messages = load_messages()
    found = False

    for msg in messages:
        for reply in msg.get('replies', []):
            if reply['id'] == reply_id:
                found = True
                if action == 'approve':
                    reply['status'] = 'approved'
                    msg_text = '回复已批准'
                elif action == 'reject':
                    msg['replies'].remove(reply)
                    msg_text = '回复已拒绝'
                else:
                    return jsonify({'success': False, 'message': '无效操作'}), 400

                save_messages(messages)
                return jsonify({'success': True, 'message': msg_text})

    if not found:
        return jsonify({'success': False, 'message': '回复不存在'}), 404


@messages_bp.route('/delete-message/<message_id>', methods=['POST'])
@login_required
def delete_message(message_id):
    messages = load_messages()
    message_to_delete = next((msg for msg in messages if msg['id'] == message_id), None)

    if not message_to_delete:
        flash('留言不存在', 'error')
    elif message_to_delete['user_id'] != current_user.id:
        flash('您只能删除自己的留言', 'error')
    else:
        try:
            messages = [msg for msg in messages if msg['id'] != message_id]
            save_messages(messages)
            flash('留言已删除', 'success')
        except Exception as e:
            logging.error(f"删除留言失败: {e}")
            flash('删除失败，请稍后再试', 'error')

    return redirect(url_for('messages.message_board'))


@messages_bp.route('/reply-message/<message_id>', methods=['POST'])
@login_required
def reply_message(message_id):
    messages = load_messages()
    content = request.form.get('content', '').strip()

    if not content:
        flash('回复内容不能为空', 'error')
    elif len(content) > 300:
        flash('回复内容不能超过300字', 'error')
    else:
        original_message = next((msg for msg in messages if msg['id'] == message_id), None)

        if not original_message:
            flash('原始留言不存在', 'error')
        else:
            new_reply = {
                'id': str(uuid.uuid4()),
                'user_id': current_user.id,
                'username': current_user.username,
                'content': content,
                'created_at': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            }

            original_message['replies'].insert(0, new_reply)

            try:
                save_messages(messages)
                flash('回复成功', 'success')
            except Exception as e:
                logging.error(f"保存回复失败: {e}")
                flash('回复失败，请稍后再试', 'error')

    return redirect(url_for('messages.message_board'))


@messages_bp.route('/upload-image', methods=['POST'])
@login_required
def upload_image():
    """处理富文本编辑器图片上传"""
    if 'file' not in request.files:
        return {'error': '没有上传文件'}, 400

    file = request.files['file']
    if file.filename == '':
        return {'error': '没有选择文件'}, 400

    if file:
        # 创建上传目录
        upload_dir = os.path.join(basedir, 'static', 'uploads', 'messages')
        os.makedirs(upload_dir, exist_ok=True)

        # 安全处理文件名
        filename = secure_filename(file.filename)
        unique_filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{filename}"
        filepath = os.path.join(upload_dir, unique_filename)

        try:
            file.save(filepath)
            # 返回相对URL路径
            image_url = url_for('static', filename=f'uploads/messages/{unique_filename}')
            return {'link': image_url}
        except Exception as e:
            logging.error(f"图片上传失败: {e}")
            return {'error': '图片上传失败'}, 500
